﻿using FineUI;
using System;
using System.Linq;
using System.Text;
using System.Web;
using ZHDJ.Core;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.BLL;
using ZHDJ.Data.DataCaching;
using ZHDJ.Data.Models.Org;
using ZHDJ.WebPage;
using ZHDJ.Data.Models.Box;
namespace ZHDJ.Web
{
    public partial class Register : System.Web.UI.Page
    {
        #region 实体上下文
        /// <summary>
        /// 数据访问 
        /// </summary>
        public static AppBoxContext DB
        {
            get
            {
                if (!HttpContext.Current.Items.Contains("__AppBoxContext"))
                {
                    HttpContext.Current.Items["__AppBoxContext"] = new AppBoxContext();
                }
                return HttpContext.Current.Items["__AppBoxContext"] as AppBoxContext;
            }
        }

        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var pickerurl = String.Format("app/Share/Picker/BranchToMemberPicker.aspx?ids=<script>{0}</script>",
                               hdBranchID.GetValueReference());
                ppBranch.OnClientTrigger2Click = Window1.GetSaveStateReference(hdBranchID.ClientID, ppBranch.ClientID)
                                                  + Window1.GetShowReference(pickerurl);

                StringBuilder js = new StringBuilder();
                js.AppendFormat(@"
                ; var pickerClientID = '{0}';
                  var pickerHdClientID = '{1}';
                  F(pickerClientID).setValue('');
                  F(pickerHdClientID).setValue('');
", ppBranch.ClientID, hdBranchID.ClientID);
                ppBranch.OnClientTrigger1Click = js.ToString();
            }
        }

        #region 数据
        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns></returns>
        public bool ChecValidateNum()
        {
            var num = this.txtValidateNum.Text.ToLower();
            if (Session["ValidateNum"] != null && Convert.ToString(Session["ValidateNum"]).ToLower() == num)
                return true;
            ImaValidateNum.ImageUrl = "app/share/ValidateNum.aspx?r=" + DateTime.Now.Ticks;
            FineUI.Alert.Show("验证码不正确！", String.Empty);
            return false;

        }

        /// <summary>
        /// 数据是否为空
        /// </summary>
        /// <returns></returns>
        public bool CheckDataEmpty()
        {

            var rs = true;
            if (string.IsNullOrEmpty(txtUserNo.Text))
            {
                txtUserNo.MarkInvalid("必填");
                rs = false;
            }

            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                txtPassword.MarkInvalid("必填");
                rs = false;
            }
            if (string.IsNullOrEmpty(txtPassword2.Text))
            {
                txtPassword2.MarkInvalid("必填");
                rs = false;
            }
            if (string.IsNullOrEmpty(txtIdentityCard.Text))
            {
                txtIdentityCard.MarkInvalid("必填");
                rs = false;
            }
            if (string.IsNullOrEmpty(txtMobileNo.Text))
            {
                txtMobileNo.MarkInvalid("必填");
                rs = false;
            }
            if (string.IsNullOrEmpty(txtEmail.Text))
            {
                txtEmail.MarkInvalid("必填");
                rs = false;
            }
            return rs;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool CheckDataRight()
        {
            var rs = true;
            if (!ValidateHelper.IsNormalChar(txtUserNo.Text))
            {
                txtUserNo.MarkInvalid("用户名只能为字母、数字和下划线");
                FineUI.Alert.Show("用户名只能为字母、数字和下划线！", String.Empty);
                rs = false;
            }
            if (this.txtPassword.Text.Trim() != this.txtPassword2.Text.Trim())
            {
                txtPassword.MarkInvalid("二次输入的密码不一致");
                txtPassword2.MarkInvalid("二次输入的密码不一致");
                txtPassword.Text = txtPassword2.Text = "";
                FineUI.Alert.Show("二次输入的密码不一致！", String.Empty);
                rs = false;
            }

            var q = DB.PartyOrgMembers;
            if (q.Any(a => a.UserNo == txtUserNo.Text.Trim()))
            {
                FineUI.Alert.Show("登陆号已存在，请重新输入！", String.Empty);
                rs = false;
            }
            if (q.Any(a => a.MobileNo == txtMobileNo.Text.Trim()))
            {
                FineUI.Alert.Show("手机号已存在，请重新输入！", String.Empty);
                rs = false;
            }
            if (q.Any(a => a.IdentityCard == txtIdentityCard.Text.Trim()))
            {
                FineUI.Alert.Show("身份证号已存在，请重新输入！", String.Empty);
                rs = false;
            }
            return rs;
        }

        /// <summary>
        /// 保存
        /// </summary>
        public void SaveData()
        {
            string BI = "";
            PartyOrgMember member = new PartyOrgMember();
            member.LoginID = StringHelper.NewID;
            member.ID = member.LoginID;
            member.UserNo = txtUserNo.Text.Trim();
            member.UserName = txtUserName.Text.Trim();
            member.Gender = rbGender.SelectedValue;
            member.WorkUnit = txtWorkUnit.Text.Trim();
            member.WorkUnit = ppBranch.Text;
            if (txtBranch.Text != "")
            {
                member.WorkUnit = txtBranch.Text;
            }
            member.BranchID = hdBranchID.Text;
            BI = ControlBusiness.GetBranchPickerText(hdBranchID.Text);
            member.UnitJob = txtUnitJob.Text.Trim();
            member.IdentityCard = txtIdentityCard.Text.Trim();
            member.MobileNo = txtMobileNo.Text.Trim();
            member.Password = PasswordUtil.CreateDbPassword(txtPassword.Text.Trim());
            member.IsAgree = true;
            member.runSate = "-1";
            member.IsFirstLogin = true;
            member.isHardParty = false;
            member.IsIncumbency = false;
            member.isPartyDeputy = false;
            member.IsPartyWorker = false;
            member.isVolunteer = false;
            member.CreateTime = DateTime.Now;
            member.pwdOverTime = Convert.ToDateTime("9999-12-31");
            member.BeRegularDate = null;
            member.JoinPartyDate = null;
            member.ModifyTimeEx = null;
            member.Birthday = null;
            member.Email = txtEmail.Text;
            DB.PartyOrgMembers.Add(member);
            if (DB.SaveChanges() > 0)
            {

                int dept = 0;

                try
                {
                    Object s = DboDept.GetDeptName(BI);

                    string ss = s.ToString();
                    if (ss != "")
                    {
                        dept = Convert.ToInt32(ss);
                    }
                    else
                    {
                        dept = 13;
                    }
                    RoleHelper.AddRole(member.LoginID, SystemParameterCaching.Get(SystemParameterKey.MassRoleID));

                    //默认密码:"e123456","A115A58E6C40DA1887F9",默认部门:"测试党委"
                    var tempSql = @" insert UserInfo (UserCode,UserName,UserPwd,DeptID,Worker,RacingFen,UserMember) 
                                        values('" + txtUserNo.Text.Trim() + "','" + txtUserName.Text.Trim() + "','A115A58E6C40DA1887F9'," + dept + ",'考生',-1,1);";
                    var powersql = @"INSERT [dbo].[UserPower] ([UserCode], [AddNews], [ManagNews], [AddForum], [ManagForum], [AddPoll], [ManagPoll], [AddRubric], [ManagRubric], [AddSubject], [ManagSubject], [AddText], [ManagText], [AddLession], [ManagLession], [CheckRubric], [AddPaper], [ManagPaper], [CheckPaper], [PaperTemple], [LookPaper], [CheckRubricF], [CheckRubricO], [CheckRubricA], [CheckRubricC], [CheckRubricT], [CheckRubricAN], [CheckRubricJ], [ManagExam], [ManagUser], [ManagMenu], [ManagSysSet], [ManagFolder], [ManagPower], [ManagRacing], [CheckPaperID], [LookPaperID], [ZiManag], [AddStudyPlan], [ManagStudyPlan], [AddExam]) 
                        VALUES (N'" + txtUserNo.Text.Trim() + "', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', N'N', NULL, NULL, N'N', N'N', N'N', N'N')";
                    SqlServerHelper.ExecuteNonQuery(tempSql);
                }
                catch (Exception)
                {

                }

                //ExceptionUtil.CatchException(OnlineStudySystem.SyncData);
               
                PageContext.RegisterStartupScript(";su();");
                //FineUI.Alert.Show("注册成功！", String.Empty,"su();");
                //RedirectTo("Login","~/login.aspx");
            }
        }

        #endregion
        #region 事件
        /// <summary>
        /// 刷新验证码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtnValidateNum_Click(object sender, EventArgs e)
        {
            ImaValidateNum.ImageUrl = "app/share/ValidateNum.aspx?r=" + DateTime.Now.Ticks;
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            if (!CheckDataEmpty())
                return;
            if (!ChecValidateNum())
                return;
            if (!CheckDataRight())
                return;
            SaveData();
        }
        #endregion
    }
}